package com.aaa.servlet;

import java.util.Map;

import javax.jws.WebResult;
import javax.servlet.annotation.WebServlet;

import com.aaa.annotation.RequestMapping;
import com.aaa.dao.UserDAO;
import com.aaa.dao.impl.UserDAOImpl;
import com.aaa.result.ResultEntity;
import com.aaa.util.SendCodeUtils;

@WebServlet("/user/*")
public class UserServlet extends BaseServlet {

	private static final long serialVersionUID = 1L;
	private UserDAO userDAO = new UserDAOImpl();
	
	@RequestMapping( url = "getUser")
	public ResultEntity  getUser(Map<String,Object> args) {
		
		Object user = session.getAttribute("user");
		
		if(user == null) {
			return new ResultEntity(10014, "对不起 没有登录呢还", null);
		}
		// 不好 因为会将用户的账号密码一并的返回
		return new ResultEntity(10015, "获取成功", user);
	}
	
	@RequestMapping( url = "login")
	public ResultEntity  login(Map<String,Object> args) {
		// 1 验证账号密码是否正确
		Map<String, Object> user = userDAO.isLogin(args);
		if(user == null) {
			// 2 不正确返回信息
			return new ResultEntity(10012, "对不起 账号或者密码不正确", null);
		}
		// 3 正确 将用户信息存储到session中 （目前先这样 以后再也不存储到session了 单机版本 祛session化）
		session.setAttribute("user", user);
		return new ResultEntity(10013, "登录成功", null);
	}
	
	
	
	@RequestMapping( url = "register")
	public ResultEntity  register(Map<String,Object> args) {
		//1 验证手机号 是否被占用
		boolean exist = userDAO.isExist(args);
		if(exist) {
			return new ResultEntity(10008, "手机号被占用", null);
		}
		
		//2验证码是否正确
		Object code = session.getAttribute("code");//后台生成的码
		Object userCode = args.get("code");
		if( ! code.equals(userCode)   ) {
			return new ResultEntity(10009, "验证码不正确", null);
		}
		
		// 3 将用户添加到数据库中
		int i = userDAO.saveUser(args);
		
		if(i>0) {
			return new ResultEntity(10010, "注册成功", null);
		}
		return new ResultEntity(10011, "注册失败", null);
	}
	
	
	@RequestMapping( url = "sendCode")
	public ResultEntity  sendCode(Map<String,Object> args) {
		//1 获取手机号
		String tel = (String) args.get("tel");
		//2生成验证码
		int d = (int) ( Math.random()*1000000 );
		String code = String.valueOf(d);
		System.out.println(code);
		//3发送短信
		SendCodeUtils.send(tel, code);
		//3.5 将短信的随机验证码存储到session中 注册的时候需要校验
		session.setAttribute("code", code);
		//4回传信息
		return new ResultEntity(10006, "发送成功", null);
	}
	
	
	
	@RequestMapping( url = "isExist")
	public ResultEntity isExist(Map<String,Object> args) {
		//1 验证账号是否正确
		boolean exist = userDAO.isExist(args);
		
		if(exist) {
			return new ResultEntity(10006, "账号已经被占用", null);
		}
		return new ResultEntity(10007, "账号可用", null);
	}
	
	

}
